package cluster

import (
	"gitee.com/easy_code/go-redis/interface/resp"
	"gitee.com/easy_code/go-redis/resp/reply"
)

// Del 删除。思路：广播将所有key发送到全部节点，然后统计删除成功的key数量
func Del(cluster *ClusterDatabase, c resp.Connection, cmdArgs [][]byte) resp.Reply {
	replies := cluster.broadcast(c, cmdArgs)
	var errReply reply.ErrorReply
	var deleted int64 = 0
	// 有错误直接返回
	for _, r := range replies {
		if reply.IsErrorReply(r) {
			errReply = r.(reply.ErrorReply)
			break
		}
		intReply, ok := r.(*reply.IntReply)
		if !ok {
			errReply = reply.MakeErrReply("error")
		}
		deleted += intReply.Code
	}
	if errReply == nil {
		return reply.MakeIntReply(deleted)
	}
	return reply.MakeErrReply("error:" + errReply.Error())
}
